<template>
    <div>
        <Modal
            v-model="modal1"
            :title=title
            width="700"
            :mask-closable=false
            @on-visible-change="change">
            <Row>
                <Form :label-width="80" inline>
                    <FormItem label="角色名称:" prop="name" style="width:100%;margin-bottom:10px;">
                        <Input :disabled='isCheck' style="width:100%;margin-bottom:12px;" v-model="name" placeholder="自定义角色名称"></Input>
                    </FormItem>

                    <FormItem label="角色模板:" prop="name" style="width:100%;margin-bottom:10px;">
                        <Select :disabled='isCheck' style="width:100%;margin-bottom:12px;" v-model="templateRole" placeholder="角色模板" @on-change="handleSelectRole">
                            <Option v-for="item in templateRoles" :value="item.id" :key="item.id">{{ item.name }}</Option>
                        </Select>
                    </FormItem>

                    <FormItem label="角色说明:" prop="name" style="width:100%;margin-bottom:10px;">
                        <Input :disabled='isCheck' style="width:100%;margin-bottom:12px;" placeholder="角色说明" v-model="description"></Input>
                    </FormItem>

                    <FormItem label="房源管理:" prop="homeManage" style="width:100%;margin-bottom:10px;">
                        <Select :disabled="true" v-model="homeManageType" placeholder="房源管理范围">
                            <Option v-for="item in homeManageTypes" :value="item.value" :key="item.label">{{ item.label }}</Option>
                        </Select>
                    </FormItem>
                </Form>
            </Row>

            <div class="staff-permission">
                <Spin v-if="loadingPermission" fix></Spin>
                <div class="staff-permission__container">
                    <div v-for="(category, categoryIndex) in permissionList" :key="category.id" class="staff-permission__row">
                        <div class="staff-permission__title">{{category.name}}</div>

                        <CheckboxGroup v-model="selectedPermissionIds">
                            <div class="staff-permission__list" v-for="(group, groupIndex) in category.groups" :key="group.id">
                                <div class="staff-permission__list__title">
                                    {{group.name}}
                                    <i-button
                                        v-if="!isDefaultPermissionGroup(group.key) && !isCheck && canNotSelectAll(group.permissions)"
                                        size="small"
                                        class="staff-permission__list__btn"
                                        @click.native="handleSelectAll(categoryIndex, groupIndex)">
                                        {{group.selectedAll ? '取消全选' : '全选'}}
                                    </i-button>
                                </div>
                                <div class="staff-permission__list__row">
                                    <Checkbox
                                        class="staff-permission__list__item"
                                        :key="permission.id"
                                        :label="permission.id"
                                        :disabled="permission.disabled"
                                        v-for="permission in group.permissions">
                                        {{permission.name}}
                                    </Checkbox>
                                </div>
                            </div>
                        </CheckboxGroup>
                    </div>
                </div>
            </div>

            <div slot="footer">
                <Button type="default" size="large" @click="cancel">取消</Button>
                <Button type="primary" size="large" v-if="!isCheck" @click="ok" :loading="isLoading">保存</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import cloneDeep from 'lodash/cloneDeep'
import { http, api } from '@/libs/http'
import dataCenter from '@/libs/dataCenter'

const defaultClassId = 9 // 其他权限 不显示
export default {
  props: {
    modal: {
      default: false
    },
    roleId: {
      required: true
    },
    roles: {
      default: []
    },
    title: '',
    roleType: {
      required: true
    }
  },
  data () {
    return {
      defaultPermissionIds: [], // 默认的权限id
      defaultPermissionGroupKeys: [ 'base' ], // 必选的permission组key
      loadingPermission: false,
      templateRole: '',
      actionInfo: [],
      name: '',
      description: '',
      indeterminate: false,
      selectedPermissionIds: [],
      permissionList: [],
      isLoading: false,
      homeManageType: 0,
      homeManageTypes: [
        {
          value: 0,
          label: '管理门店所有房源'
        },
        {
          value: 1,
          label: '管理门店指定房源'
        }
      ],

      defaultClassId
    }
  },

  computed: {
    modal1: {
      get: function () {
        return this.modal
      },
      set: function (v) {
        this.$emit('update', v)
      }
    },
    isCheck: function () {
      return this.title === '查看角色'
    },
    templateRoles () {
      const templateRoles = []
      this.roles.forEach(item => {
        if (item.type === 0 && item.id !== 100) {
          // 经典角色
          templateRoles.push({
            name: item.name,
            permission_groups: [],
            id: item.id
          })
        }
      })
      return templateRoles
    },
    ...mapState(['app'])
  },
  methods: {
    // 查看的时候检查是否有全部子全选
    groupHasAllPermission (permissions) {
      if (!this.selectedPermissionIds || this.selectedPermissionIds.length === 0) return false
      const ids = permissions.map(p => p.id)
      return !ids.some(id => !this.selectedPermissionIds.includes(id)) // 如果有一个id不在范围内则不全选
    },
    canNotSelectAll (groupPermissions) {
      if (!groupPermissions) return true
      return groupPermissions.some(p => !p.disabled) // 有一个是可选的就是可用全选
    },
    handleSelectAll (categoryIndex, groupIndex) {
      const group = this.permissionList[categoryIndex].groups[groupIndex]
      const isAdd = group.selectedAll === false
      this.$set(this.permissionList[categoryIndex].groups[groupIndex], 'selectedAll', !group.selectedAll)
      const permissionIds = group.permissions.reduce((result, p) => {
        if (p.disabled) return result
        return result.concat([p.id])
      }, [])
      if (isAdd) {
        this.selectedPermissionIds = [ ...new Set([ ...this.selectedPermissionIds, ...permissionIds ]) ]
      } else {
        this.selectedPermissionIds = this.selectedPermissionIds.filter(check => !permissionIds.includes(check))
      }
    },
    cancel () {
      this.modal1 = false
    },

    async change (val) {
      if (!val) {
        this.name = ''
        this.templateRole = ''
        this.description = ''
        this.homeManageType = 0
      }

      if (val) {
        await this.getPermissions()
      }

      if (val && this.roleId) {
        this.getRoleById(this.roleId)
      } else {
        this.selectedPermissionIds = []
        this.addDefaultPermission()
      }
    },

    async getRoleById (roleId, isTemplate) {
      if (!roleId) return
      this.loadingPermission = true
      const res = await http.req(api.role_info, [roleId], null)
      this.loadingPermission = false
      if (!res) return
      if (!isTemplate) {
        this.name = res.name
        this.description = res.description || '无'
        this.homeManageType = res.home_appointed || 0
      }
      this.selectedPermissionIds = res.permission_groups.reduce((result, category) => {
        return result.concat(category.permissions.map(p => p.id))
      }, [])
      if (isTemplate) this.addDefaultPermission()
    },

    ok () {
      if (this.isCheck) {
        // 经典角色
        this.modal1 = false
        return
      }

      const classicRoles = ['管理员', '管家', '财务', '店长']
      const roleName = this.name.trim()

      if (!roleName) {
        this.$Message.error('请填写角色名称')
        return
      }

      if (classicRoles.indexOf(roleName) > -1) {
        this.$Message.error('角色名称不能跟经典角色相同')
        return
      }

      const params = {
        name: roleName,
        permission_ids: this.selectedPermissionIds,
        description: this.description.trim() || '无'
      }

      if (this.homeManageType) {
        params.home_appointed = 1
      }

      this.addRole(params, this.roleId)
    },

    // 添加角色
    addRole (params, roleId) {
      if (this.isLoading) {
        return
      }

      // util.log(params, roleId)
      // return

      this.isLoading = true
      if (roleId) {
        // 编辑角色
        http.request(this, api.role_update, [roleId], params, (res, err) => {
          this.isLoading = false
          if (res) {
            this.modal1 = false
            this.$emit('updateList')
            this.$Message.success('修改角色成功')
          }
        })
      } else {
        // 新增角色
        http.request(this, api.role_create, null, params, (res, err) => {
          this.isLoading = false
          if (res) {
            this.modal1 = false
            this.$emit('updateList')
            this.$Message.success('添加角色成功')
          }
        })
      }
    },

    // 获取所有权限
    getPermissions () {
      return new Promise(resolve => {
        this.loadingPermission = true
        const currentUserPermissionIds = this.app.userCurrentPermissions.map(p => p.id)
        dataCenter.getPermissions(this, res => {
          this.loadingPermission = false
          let defaultPermissionIds = []
          const permissions = cloneDeep(res)
          permissions.forEach(category => {
            category.groups.forEach(group => {
              /** group全选配置 */
              group.selectedAll = false
              group.permissions.forEach(p => {
                /**
                                 * 查看不可更改
                                 * 在默认分配组的权限不可更改
                                 * 当前用户没有的权限不可更改
                                 */
                p.disabled = this.isCheck ||
                                    this.isDefaultPermissionGroup(group.key) ||
                                    !currentUserPermissionIds.includes(p.id)
              })
              /** 如果当前group是默认组, 写入group下的permission id到默认权限id中 */
              if (this.defaultPermissionGroupKeys.includes(group.key)) {
                defaultPermissionIds = defaultPermissionIds.concat(group.permissions.map(p => p.id))
              }
            })
          })
          this.defaultPermissionIds = defaultPermissionIds
          this.permissionList = permissions
          resolve()
        })
      })
    },

    handleSelectRole (id) {
      this.getRoleById(id, true)
    },

    isDefaultPermissionGroup (key) {
      return this.defaultPermissionGroupKeys.includes(key)
    },
    /**
         * 权限变化之后, 将没有添加的默认权限添加到结果中
         */
    addDefaultPermission () {
      const shouldAddPermission = this.defaultPermissionIds.filter(id => !this.selectedPermissionIds.includes(id))
      if (shouldAddPermission.length) {
        this.selectedPermissionIds = this.selectedPermissionIds.concat(shouldAddPermission)
      }
    }
  }
}
</script>

<style lang="less">
@import '../staff.less';
.role-wrapper {
    background-color: #f3f3f3;
    border-radius: 4px;
    padding: 5px 15px 5px 15px;
    max-height: 320px;
    overflow: auto;

    .role-item {
        padding-bottom: 8px;
        border-bottom: 1px solid #dddee1;
    }
    .role-item:last-child {
        padding-bottom: 8px;
        border-bottom: none;
    }
}
</style>
